package com.javaweb.bookstore.servlet;

import com.javaweb.bookstore.*;
import com.javaweb.bookstore.component.IBookManager;
import com.javaweb.bookstore.component.JdbcBookManager;
import com.javaweb.bookstore.entity.Book;
import com.javaweb.bookstore.entity.ResponseEntity;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.io.IOException;
import java.util.*;

@WebServlet("/book")
public class BookServlet extends HttpServlet {
    IBookManager manager;




    @Override
    public void init() throws ServletException {
       super.init();

    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {



        String operation = req.getParameter("operation");
        if(operation.equals("create")) {
            String bookName = req.getParameter("bookName");
            String bookPrice = req.getParameter("bookPrice");
            String desc = req.getParameter("bookDesc");
            Map<String, String[]> ps = req.getParameterMap();
            int bprice = Integer.parseInt(bookPrice);
            Book book = new Book();
            book.setName(bookName);
            book.setPrice(bprice);
            book.setId(UUID.randomUUID().toString());
            book.setDesc(desc);
            manager.createBook(book);
            //存库
            ResponseEntity re = new ResponseEntity(true, "create success!", book);
            String jsonString = Utils.obj2json(re);
            resp.getWriter().println(jsonString);
            return;
        }

        if(operation.equals("remove")) {
            String id = req.getParameter("id");
            manager.removeBook(id);
            ResponseEntity re = new ResponseEntity(true, "remove success!", null);
            String json = Utils.obj2json(re);
            resp.getWriter().println(json);
            return;
   
        }


        ResponseEntity re = new ResponseEntity(false, "unsupported operation!", null);
        String json = Utils.obj2json(re);
        resp.getWriter().println(json);


    }




    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                resp.getWriter().println("hello post merhod is used!");
    }

   
}
